<?php
/**
 * Created by PhpStorm.
 * User: dale
 * Date: 2017/11/2
 * Time: 上午11:49
 */

namespace Admin\Frontend\Controllers;


use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\log\XhlogUserTch;
use Admin\Models\res\XhresArticle;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\school\XhschoolPublicClass;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\sys\XhsysTemplate;
use Admin\Models\sys\XhsysUserTch;

use Admin\Models\track\XhtrackTch;
use Admin\Models\user\XhsysUser;
use Helpers\Assets;
use Helpers\Hrm;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\UserPower;
use Helpers\XhException;
use Modules\Msg;
use Modules\Power;
use Modules\School;
use Services\App;

class TchController extends ControllerBase
{
    private static $enums = [
        'iUserSex'  => ['1' => '男', 2 => '女'],
        'logTch'    => [1 => '基本信息', 2 => '跟踪情况', 3 => '公开课', 4 => '公开课反馈'],
        'type'      => [0 => '不计入考核' , 1 => '计入考核' ],
    ];



    private function praseTchLog($iUserId,$type){
        $tch   = XhsysUser::findFirst($iUserId)->toArray();
        $tTime = date('Y-m-d',time());
        $log = XhlogUserTch::findFirst([
            'conditions' => 'tTime = :tTime: AND iUserId = :iUserId:',
            'bind'       => ['tTime'=>$tTime,'iUserId'=>$iUserId]
        ]);
        if(!$log){  //如果不存在
            $log = new XhlogUserTch();
            $log->sTypes = ','.$type.',';
        }else{
            $arr   = array_values(array_filter(explode(',',$log->sTypes)));
            $arr[] = $type;
            $arr   =array_unique($arr);
            $log->sTypes = ','.implode(',',$arr).',';
        }
        $log->iUserId   = $iUserId;
        $log->iSchoolId = $tch['iSchoolId'];
        $log->tTime     = $tTime;

        $res=$log->save();
        return $res;
    }

    public function homeAction(){
        try{
            $builder=$this->modelsManager->createBuilder()
                ->columns("p.iPCId,p.iUserId,p.tStartTime,p.iPCType,u.iSchoolId,s.sSchoolName,u.sUserName")
                ->from(['p'=>'Admin\Models\school\XhschoolPublicClass'])
                ->where('p.bDelete=0');
            $builder->andWhere('p.tStartTime >= :today:',array('today'=>date('Y-m-d',strtotime('now'))))->orderBy('p.tStartTime desc,p.tCreateDate');
            $builder->leftJoin('Admin\Models\user\XhsysUser','u.iUserId=p.iUserId','u')
                    ->leftJoin('Admin\Models\school\XhschoolInfo','s.iSchoolId=u.iSchoolId','s')
                    ->limit(6);
            $pClasses=$builder->getQuery()->execute()->toArray();
        }catch (\Exception $e){
            die($e->getMessage());
        }

        $enums['iPCType'] = XhsysEnum::getEnumByNodeName('公开课类别');
        $pClasses = array_reverse($pClasses); //倒置数组
        foreach ($pClasses as $index=>$pClass){
            $pClasses[$index]['iPCType']=$enums['iPCType'][$pClass['iPCType']];
            $pClasses[$index]['tStartTime']=date('Y-m-d h:i',strtotime($pClass['tStartTime']));
        }
        $this->view->pick('tch/home');
        Assets::importJs('../ims/js/myTool.js');
        Assets::importJs('js/tch/home.js');

        $this->view->setVars([
            'pClasses'=>$pClasses,
        ]);
    }


    public function pClassDetailAction(){
        try{
            $iPCId = $this->request->getQuery('iPCId') or die('缺少参数');
            $this->view->pick('tch/pClassDeail');
            Assets::importJs('../ims/js/myTool.js');
//        Assets::importJs('js/tch/home.js');
            $builder=$this->modelsManager->createBuilder()
                ->columns("p.iPCId,p.iUserId,p.tStartTime,p.iPCType,p.mContent,u.iSchoolId,s.sSchoolName,u.sUserName,
                       p.sPlace ,p.iStuNum,p.iAttendNum,p.sAttendClass,p.mAttendences,p.mDesc,p.iRunChargeId,
                       p.iAtClassChargeId,p.iWebChargeId,p.iTechChargeId,p.iMarkChargeId,p.mEvaluate,
                       p.iEvalId,p.tEvalTime,up.sSelfPhone")
                ->from(['p'=>'Admin\Models\school\XhschoolPublicClass'])
                ->where('p.bDelete=0 AND iPCId=:iPCId:',array('iPCId'=>$iPCId));
            $builder->leftJoin('Admin\Models\user\XhsysUser','u.iUserId=p.iUserId','u')
                ->leftJoin('Admin\Models\user\XhsysUser','p.iEvalId=up.iUserId','up')
                ->leftJoin('Admin\Models\school\XhschoolInfo','s.iSchoolId=u.iSchoolId','s');
            $info = $builder->getQuery()->execute()->toArray();

            $info[0]['tStartTime'] = date('Y-m-d h:i',strtotime($info[0]['tStartTime']));

            $this->runPhoneById($info,['iRunChargeId'=>'runPhone','iAtClassChargeId'=>'atcPhone','iWebChargeId'=>'webPhone','iTechChargeId'=>'techPhone','iMarkChargeId'=>'markPhone'],true);
            $this->runStaffNameById($info,['iAtClassChargeId'=>'iAtClassChargeId','iRunChargeId'=>'iRunChargeId','iWebChargeId'=>'iWebChargeId','iTechChargeId'=>'iTechChargeId','iMarkChargeId'=>'iMarkChargeId'],true);
            $info = $info[0];
            $this->view->setVars([
                'info'=>$info,
            ]);
        }catch (\Exception $e){
            die($e->getMessage());
        }

    }


    /**
     * 教师Tab
     * @param $iUserId
     * created by dale 2017/11/2
     * modify by sqb 20181224
     */
    public function tchTabAction($data=null)
    {
        $iUserId = explode('_', $data)[0];
        $tab = explode('_', $data)[1];

        try{
            UserPower::checkUserPower('School_List_Tch') or UserPower::checkUserPower('School_TeacherList') or  die('缺少权限');
            if (!$iUserId) {
                $this->sendViewError('缺少id');
            }
            $this->view->pick('tch/tchTab');
            Assets::datetimePicker();
            Assets::select2();
            Assets::importJs('../ims/js/myTool.js');
            Assets::importJs('js/tch/tchTab.js');
            $builder=$this->modelsManager->createBuilder()
                ->columns('u.iUserId,u.sUserName,u.iUserSex,t.iSubject,u.sHobby,s.sSchoolName,u.sSelfPhone,u.sBirthday,u.bHistory,t.bImportant,t.sSubjects,
                               t.iCurGrade,t.sDuty,t.bExcellent,t.bMine,t.mEvaluate,s.iSchoolId,t.iProficiency,t.sAdminClass,t.sEBagClass,t.iType,t.bStatsLog')
                ->from(['u'=>'Admin\Models\user\XhsysUser'])
                ->leftJoin('Admin\Models\sys\XhsysUserTch','u.iUserId=t.iUserId','t')
                ->leftJoin('Admin\Models\school\XhschoolInfo','u.iSchoolId=s.iSchoolId','s')
                ->where('u.iUserId=:iUserId: AND u.bDelete=0',array('iUserId'=>$iUserId));
            $tchInfo = $builder->getQuery()->execute()->toArray();
            $tchInfo = $tchInfo[0];

            $newBuilder = $this->modelsManager->createBuilder()
                    ->columns('iUserId')
                    ->from('Admin\Models\user\XhsysUser')
                    ->where('bDelete = 0 and bHistory = 0 and bDisable = 0 and iUserType = 4 and iSchoolId = :iSchoolId:', ['iSchoolId' => $tchInfo['iSchoolId']]);

            $prev = clone $newBuilder;
            $prev->andWhere('iUserId < :iUserId: ', ['iUserId' => $tchInfo['iUserId']]);
            $prev = $prev->limit(1)->getQuery()->execute()->toArray();
            $prev = Tool::getValue($prev, 0, []);
            $prev = Tool::getValue($prev, 'iUserId', null);
            $next = clone $newBuilder;
            $next->andWhere('iUserId > :iUserId:', ['iUserId' => $tchInfo['iUserId']]);
            $next = $next->limit(1)->getQuery()->execute()->toArray();
            $next = Tool::getValue($next, 0, []);
            $next = Tool::getValue($next, 'iUserId', null);
            $tchList['prevId'] = $prev;
            $tchList['nextId'] = $next;
            return $this->view->setVars([
                'iUserSex' => self::$enums['iUserSex'],
                'tchInfo'  => json_encode($tchInfo),
                'iUserId'  => $iUserId,
                'title'    => $tchInfo['sSchoolName'].'&nbsp;&nbsp;'.$tchInfo['sUserName'],
//            'addPower' => UserPower::checkUserPower('School_List_Tch_Add'),
                'power' => [
                    'info'=>UserPower::checkUserPower('School_List_Tch_Edit')
                        and School::hasPower($tchInfo['iSchoolId'], true),
                    'track'=>UserPower::checkUserPower('School_Teacher_Track'),
                    'pClass'=>UserPower::checkUserPower('School_Teacher_PublicClass')],
                'iProficiency' => XhsysEnum::getEnumByNodeName('熟练程度'),
                'iSubject'     => XhsysEnum::getEnumByNodeName('学科'),
                'iCurGrade'    => XhsysEnum::getEnumByNodeName('年级'),
                'schoolId'     => $tchInfo['iSchoolId'],
                'iType'        => self::$enums['type'],
                'tchList'      => $tchList,
                'tab'          => $tab
            ]);
        }catch (\Exception $e){
            return $this->sendViewError($e->getMessage());
        }

    }

    /**
     * 保存教师
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 2017/11/2
     * modify by dale 20180727
     */
    public function saveTchAction(){
        try {
            $sSubjects = $this->request->getPost('sSubjects');

            if (!Power::exist('School_List_Tch_Edit')) {
                return $this->sendErrorResponse(403, '没有权限');
            }
            $iUserId = $this->request->getPost('iUserId');
            if (!$iUserId) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $user = XhsysUser::findFirst([
                'conditions' => 'bDelete=0 AND iUserId=:iUserId:',
                'bind' => ['iUserId' => $iUserId]
            ]);
            if (!$user) {
                return $this->sendErrorResponse(400, '未找到该教师');
            }
            if (!School::hasPower($user->iSchoolId, true)) {
                return $this->sendErrorResponse(403, '缺少学校管理权限');
            }
            $user->assign($this->request->getPost());
            $user->saveWithOldData();
            $tch = XhsysUserTch::findFirst([
                'conditions' => 'bDelete=0 AND iUserId=:iUserId:',
                'bind' => ['iUserId' => $iUserId]
            ]);
            if (!$tch) {
                $tch = new XhsysUserTch();
            }
            $tch->assign($this->request->getPost());
            $tch->sSubjects  = isset($sSubjects) ? implode(',',$sSubjects) : null ;
            $tch->bExcellent = $this->request->getPost('bExcellent') == '' ? null : $this->request->getPost('bExcellent');
            $tch->bMine = $this->request->getPost('bMine') == '' ? null : $this->request->getPost('bMine');
            $tch->iProficiency = $this->request->getPost('iProficiency') ?: null;
            $tch->iSubject     = $this->request->getPost('iSubject') ?: null;
            $tch->iCurGrade    = $this->request->getPost('iCurGrade') ?: null;
            $tch->bStatsLog    = $this->request->getPost('bStatsLog','int',0);
            if ($tch->save()) {
                $this->praseTchLog($iUserId, 1);
                return $this->sendSuccessResponse('保存成功');
            } else {
                return $this->sendErrorResponse(500, '保存失败');
            }
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 教师跟踪
     * created by dale 2017/11/2
     */
    public function tchTrackAction($type=''){
        Assets::viewer();
        Assets::datetimePicker();
        $this->di->get('assets')
            ->addCss('assets/fileinput/fileinput.css')
            ->addJs('../customer/js/fileinput.min.js')//修改过的
            ->addJs('../customer/js/zh.js');
        Assets::importJs('../customer/js/myMain.js');
        Assets::importJs('js/tch/tchTrack.js');
        $this->view->pick('tch/tchTrack');
        if($type == '2'){
            $addPower = false;
            $tpPower  = false;
            $type     = '2';
        }else{
            $addPower = UserPower::checkUserPower('School_Teacher_Track_Add');
            $tpPower  = UserPower::checkUserPower('School_TeacherList_Tp');
            $type     = '1';
        }
        $this->view->setVars([
            'addPower'  => $addPower,
            'tpPower'   => $tpPower,
            'type'      => $type,
            'trackType' => XhsysEnum::getEnumByNodeName('教师跟踪类型'),
        ]);
    }

    /**
     * 获取数据
     * @return string
     * created by dale 2017/11/2
     */
    public function getTraceAction(){
        $iUserId   = $this->request->getPost('iUserId', 'int') or die('参数不足');
        $type      = $this->request->getPost('type', 'string');
        $trackType = $this->request->getPost('trackType','string');
        $conditions =[
            'conditions' => 'bDelete=0 AND iUserId = :iUserId:',
            'bind'       => ['iUserId'=>$iUserId],
            'order'      => 'tCreateDate desc'
        ];
        if ($trackType){
            $conditions['conditions'] .= 'AND iTrackType = :iTrackType:';
            $conditions['bind']  = array_merge($conditions['bind'],['iTrackType'=>$trackType]);
        }
        $objs = XhtrackTch::find($conditions);
        if($type =='2'){
            $showDelete  = false;
            $showEdit    = false;
        }else{
            $showDelete  = UserPower::checkUserPower('School_Teacher_Track_Del');
            $showEdit    = UserPower::checkUserPower('School_Teacher_Track_Edit');
        };

        return json_encode(array(
            'showDelete' => $showDelete,
            'showEdit' => $showEdit,
            'data' => $this->pkTraceData($objs->toArray(),false)
        ));
    }

    /**
     * 处理数据
     * @param $traceArray
     * @return array
     * created by dale 2017/11/2
     */
    private  function pkTraceData($traceArray,$is_pc)
    {
        $filePath = Main::getConfigByName('customer')['downUrl'];
        $newArray = [];
        $enums['iPCType']=XhsysEnum::getEnumByNodeName('公开课类别');
        $enums['iTrackType']=XhsysEnum::getEnumByNodeName('教师跟踪类型');
        $ids = array_values(array_unique(array_filter(array_column($traceArray,'iCreateUserId'))));
        $powerArr = $this->checkPower($ids);
        Main::runUserNameById($traceArray, ['iLastModifyUserId'=>'sLastModifyUserName','iCreateUserId'=>'sCreateUserName'], true);
        foreach ($traceArray as $trace) {
            $item = array(
                'imgPath' => $filePath,
                'filePath' => $filePath,
                'images' => $trace['sImages'],
                'files' => $trace['sFiles'],
                'footer' => array(
                    'left' => '修改时间:' . $trace['tLastModifyDate'] . '&nbsp;&nbsp;修改人:' . $trace['sLastModifyUserName'],
                    'right' => '创建时间:' . $trace['tCreateDate'] . '&nbsp;&nbsp;创建人:' . $trace['sCreateUserName'],
                ),
                'showCheck' => $powerArr[$trace['iCreateUserId']],
            );
            if($is_pc){
                $item['id']    = $trace['iPCId'];
                $item['title'] = '<b>时间:</b>&nbsp;&nbsp;'.date('Y-m-d h:i',strtotime($trace['tStartTime'])).'&nbsp;&nbsp;<b>地点:</b>&nbsp;&nbsp;'.$trace['sPlace'].
                                  '&nbsp;&nbsp;<b>学生人数:</b>&nbsp;&nbsp;'.$trace['iStuNum'].'&nbsp;&nbsp;<b>听课人数:</b>&nbsp;&nbsp;'.$trace['iAttendNum'].
                                  '&nbsp;&nbsp;<b>公开课类型:</b>&nbsp;&nbsp;'.$enums['iPCType'][$trace['iPCType']].'&nbsp;&nbsp;';
                $item['time']  =  $trace['tStartTime'];
                $item['content'] = str_replace(array("\r\n", "\r", "\n"),'<br>',$trace['mContent']);
                $item['retain']  =  '<p style="margin: 0px"><b>班级:</b>&nbsp;&nbsp;'.$trace['sAttendClass'].'</p>'.
                                    '<b>听课人员情况:</b>&nbsp;&nbsp;'.str_replace(array("\r\n", "\r", "\n"),'<br>',$trace['mAttendences']).'<br>'.
                                    '<p style="margin: 0px"><b>备注:</b>  '.str_replace(array("\r\n", "\r", "\n"),'<br>',$trace['mDesc']).'</p>';
            }else{
                $item['id']      = $trace['iTTchId'];
                $item['title']   = '<b>跟踪时间:</b>&nbsp;&nbsp;' . date('Y-m-d',strtotime($trace['tTrackTime']));
                if($trace['iTrackType'] != null){
                    $item['title'] .='&nbsp;&nbsp;&nbsp;&nbsp;<b>跟踪类型：</b>&nbsp;'.$enums['iTrackType'][$trace['iTrackType']];
                }

                $item['time']    =  $trace['tTrackTime'];
                $item['content'] = '';
                $item['retain']  ='<p style="margin: 0px;position:relative;z-index: 1">'.
                                        '<b>沟通目的:</b><br>'.str_replace(array("\r\n", "\r", "\n"),'<br />',$trace['mPurpose']).'<br>'.
                                        '<b>沟通内容:</b><br>'.str_replace(array("\r\n", "\r", "\n"),'<br />',$trace['mContent']).'<br>'.
                                        '<b>沟通结果:</b><br>'.str_replace(array("\r\n", "\r", "\n"),'<br />',$trace['mResult']).'<br>'.
                                        '<b>原因分析:</b><br>'.str_replace(array("\r\n", "\r", "\n"),'<br />',$trace['mAppUse']).'<br>'.
                                        '<b>审核理由:</b><br>'.str_replace(array("\r\n", "\r", "\n"),'<br />',$trace['mCheck']).'<br>'.
                                  '</p>';
                if($trace['iState'] == 1) {
                    $item['retain'] .= '<div style="position:absolute;height: 100px;width: 100px;z-index: 0;bottom: 20px;right: 20px;"><img src="http://xuehaifile.oss-cn-hangzhou.aliyuncs.com/xhtest/f3f03dfae59741e1b1529c6f10bc7e37.png" style="width: 100%;height: 100%;opacity: 0.2;"></div>';
                }else if($trace['iState'] == 2){

                    $item['retain'] .= '<div style="position:absolute;height: 100px;width: 100px;z-index: 0;bottom: 20px;right: 20px;"><img src="http://xuehaifile.oss-cn-hangzhou.aliyuncs.com/xhtest/ccb87932a83a440ca717eeb00ddd8ef4.png" style="width: 100%;height: 100%;opacity: 0.2;"></div>';
                }else if($trace['iState'] == 3){
                    $item['retain'] .= '<div style="position:absolute;height: 100px;width: 114px;z-index: 0;bottom: 20px;right: 20px;"><img src="http://xuehaifile.oss-cn-hangzhou.aliyuncs.com/xhtest/b392e44af9674f0cb56fb279a5b79e14.png" style="width: 100%;height: 100%;opacity: 0.5;"></div>';
                }
            }
           $newArray[]=$item;
        }
        return $newArray;
    }


    public function checkPower($ids){
        if($ids ==[]){
            return [];
        }
        $powerArr = [];

        $powerIds = Hrm::getInChargeUserIds();
        if(is_bool($powerIds) === true){
            foreach ($ids as $id){
                $powerArr[$id] = $powerIds;
            }
        }else{
            $powerIds = array_column($powerIds,'iUserId','iUserId');
            foreach ($ids  as $id){
                if(isset($powerIds[$id])){
                    $powerArr[$id] = true;
                }else{
                    $powerArr[$id] = false;
                }
            }
        }
        return $powerArr;
    }

    /**
     * 表单
     * created by dale 2017/11/2
     */
    public function trackFormAction(){
        $iTTchId = $this->request->getQuery('iTTchId');
        Assets::datetimePicker();
        $this->di->get('assets')
            ->addCss('assets/fileinput/fileinput.css')
            ->addJs('../customer/js/fileinput.min.js')//修改过的
            ->addJs('../customer/js/zh.js');
        Assets::importJs('../customer/js/myMain.js');
        $this->view->pick('tch/trackForm');
        Assets::importJs('js/tch/trackForm.js');
        $check='';
        if($iTTchId){
            $track = XhtrackTch::findFirst($iTTchId)->toArray();
            $track['tTrackTime'] = date('Y-m-d',strtotime($track['tTrackTime']));
            if(Main::getLoginUserInfo('logonName') != 'admin'
                && Main::getLoginUserInfo('userId') != $track['iCreateUserId'] ){
                $check='parent.$(\'#bt_modal_confirm\').hide();';
            }
            $track = json_encode($track);
            if(!UserPower::checkUserPower('School_Teacher_Track_Edit')){
                $check='parent.$(\'#bt_modal_confirm\').hide();';
            }
        }else{
            $track = '1';
            if(!UserPower::checkUserPower('School_Teacher_Track_Add') ){
                $check='parent.$(\'#bt_modal_confirm\').hide();';
            }
        }
        $tps = XhsysTemplate::find([
            'columns'    => 'iTPId,sTPName',
            'conditions' => 'bDelete=0 AND iTPType = :iTPType:',
            'bind'       => ['iTPType' => 1],
        ]);
        $tps = array_column($tps->toArray(),'sTPName','iTPId');
        $this->view->setVars([
            'trackInfo'=>$track,
            'check'=>$check,
            'tps'=>$tps,
            'types' => XhsysEnum::getEnumByNodeName('教师跟踪类型'),
        ]);
    }

    /**
     * 保存
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/11/2
     */
    public function saveTrackAction(){
        try{
            $iTTchId = $this->request->getPost('iTTchId');
            $iUserId = $this->request->getPost('iUserId');
            if(!$iUserId){
                return $this->sendErrorResponse(400, '缺少参数');
            };
            if($iTTchId){
                if (!Power::exist('School_Teacher_Track_Edit')) {
                    return $this->sendErrorResponse(403, '缺少权限');
                }
                $obj = XhtrackTch::findFirst($iTTchId);
            }else{
                if (!Power::exist('School_Teacher_Track_Add')) {
                    return $this->sendErrorResponse(403, '缺少权限');
                }
                $obj = new XhtrackTch();
            }
            $obj->assign($this->request->getPost());
            if(!$iTTchId){
                $check=XhtrackTch::findFirst([
                    'conditions' => 'mContent=:mContent: AND bDelete=0 AND iUserId=:iUserId:',
                    'bind'       => ['mContent'=>$this->request->getPost('mContent'),'iUserId'=>$this->request->getPost('iUserId')],
                ]);
                if($check){
                    return $this->sendErrorResponse(500,'无法保存相同的内容');
                }
            }
            if($obj->save()){
                if(!$iTTchId){
                    $this->praseTchLog($iUserId,2); //记日志
                    $chargerId = Hrm::getLeader($obj->iCreateUserId);
                    if ($chargerId !== false) {
//                        Msg::insertWPageUserMsg(
//                            '教师日志',
//                            'tch_log',
//                            $obj->iTTchId,
//                            '您有新的教师日志需审核',
//                            Tool::buildUrl('tch_log/index', ['iTTchId' => $obj->iTTchId]),
//                            [$chargerId]
//                        );
                    }
                }
                return $this->sendSuccessResponse('保存成功');
            }else{
                return $this->sendErrorResponse(500,'保存失败');
            }
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }

    }

    /**
     * 删除
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/11/2
     *
     * modify by dale 20181113
     */
    public function delTrackAction()
    {
        if (!Power::exist('School_Teacher_Track_Del')) {
            return $this->sendErrorResponse(403 , '缺少权限');
        }
        $iTTchId = $this->request->getPost('iTTchId');
        if (!$iTTchId) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $obj = XhtrackTch::findFirst($iTTchId);
        if(Main::getLoginUserInfo('logonName') != 'admin'
            && Main::getLoginUserInfo('userId') != $obj->iCreateUserId){
            return $this->sendErrorResponse(403,'没有权限');
        }
        $obj->bDelete =1;
        if ($obj->save()) {
            return $this->sendSuccessResponse('删除成功');
        }else{
            return $this->sendErrorResponse(400,'删除失败');
        }
    }

    /**
     * 删除公开课
     *
     *
     * created by dale 2017/11/7
     */
    public function delClassAction(){
        if(!UserPower::checkUserPower('School_Teacher_PublicClass_Del')){
            return $this->sendErrorResponse(400,'缺少权限');
        }
        $ids = $this->request->getPost('ids');
        if(!$ids){
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $ids =explode(',',$ids);
        $res=XhschoolPublicClass::deleteRecord('iPCId',$ids);
        if($res){
            return $this->sendSuccessResponse('删除成功');
        }else{
            return $this->sendErrorResponse('删除失败');
        }
    }

    /**
     *
     * @return string
     * created by dale 2017/11/2
     */
    public function ajaxUploadAction()
    {
        $this->view->disable();
        $iUserId = $this->request->getQuery('iUserId', 'string') or die('缺少参数id');
        $this->request->hasFiles() or die('没有文件上传');

        $file = $this->request->getUploadedFiles()[0];
        $savePath = Main::getConfigByName('customer')['savePath'];

        if (!is_dir($savePath)) {
            mkdir($savePath, 0777, true) or die($savePath . '创建失败');
        }
        $root = realpath($savePath);
        substr($root, strlen($root) - 1, strlen($root)) == '/' or $root .= '/';

        $extension = strtolower($file->getExtension());

        if ($extension == 'jpg' || $extension == 'png' || $extension == 'gif' || $extension == 'jpeg') {
            $subDirName = '/img/';
        } else {
            $subDirName = '/file/';
        }
        $dirPath = $root . 'Tch'.$iUserId . $subDirName;
        if (!is_dir($dirPath)) {
            mkdir($dirPath, 0777, true) or die($dirPath . '创建失败');
        }
        $url = 'Tch'.$iUserId . $subDirName . md5_file($file->getTempName()) . '.' . $file->getExtension();
        $filePath = $dirPath . md5_file($file->getTempName()) . '.' . $file->getExtension();

        $name = $file->getName();
        $file->moveTo($filePath);

        return json_encode(array('url' => $url, 'fileName' => $name));
    }

//    private  function pkOneTraceData($trace,$is_pc)
//    {
//        $enums['iPCType']=XhsysEnum::getEnumByNodeName('公开课类别');
//        $ImgPath = Main::getConfigByName('customer')['downUrl'];
//        $filePath = Main::getConfigByName('customer')['downUrl'];
//        $item = array(
//            'imgPath' => $filePath,
//            'filePath' => $filePath,
//            'images' => $trace['sImages'],
//            'files' => $trace['sFiles'],
//            'footer' => array(
//                'left' => '修改时间:' . $trace['tLastModifyDate'] . '&nbsp;&nbsp;修改人:' . XhsysUser::findFirst($trace['iLastModifyUserId'])->toArray()['sUserName'],
//                'right' => '创建时间:' . $trace['tCreateDate'] . '&nbsp;&nbsp;创建人:' . XhsysUser::findFirst($trace['iCreateUserId'])->toArray()['sUserName'],
//            ),
//        );
//        if($is_pc){
//            $item['id']    = $trace['iPCId'];
//            $item['title'] = '<b>时间:</b>&nbsp;&nbsp;'.date('Y-m-d h:i',strtotime($trace['tStartTime'])).'&nbsp;&nbsp;<b>地点:</b>&nbsp;&nbsp;'.$trace['sPlace'].
//                '&nbsp;&nbsp;<b>学生人数:</b>&nbsp;&nbsp;'.$trace['iStuNum'].'&nbsp;&nbsp;<b>听课人数:</b>&nbsp;&nbsp;'.$trace['iAttendNum'].
//                '&nbsp;&nbsp;<b>公开课类型:</b>&nbsp;&nbsp;'.$enums['iPCType'][$trace['iPCType']].'&nbsp;&nbsp;<b>班级:</b>&nbsp;&nbsp;'.$trace['sAttendClass'];
//            $item['time']  =  $trace['tStartTime'];
//            $item['content'] = str_replace(array("\r\n", "\r", "\n"),'<br>',$trace['mContent']);
//            $item['retain'] = '<b>出席人员:</b>&nbsp;&nbsp;'.$trace['mAttendences'];
//        }else{
//            $item['id']    = $trace['iTTchId'];
//            $item['title'] = '<b>跟踪时间:</b>&nbsp;&nbsp;' . date('Y-m-d',strtotime($trace['tTrackTime']));
//            $item['time']  =  $trace['tTrackTime'];
//            $item['content'] = str_replace(array("\r\n", "\r", "\n"),'<br>',$trace['mContent']);
//        }
//
//        return $item;
//
//    }


    /**
     * 删除图片,更新数据库中记录,删除服务器上的文件
     * @param $fileType
     * created by dale 2017/6/30 下午3:23
     * modify by dale 20180508  添加文件删除
     */
    public function ajaxDeleteAction($fileType=null)
    {
        $this->view->disable();
        $id = $this->request->getPost('id', 'string') or die('缺少参数id');
        $rmId = $this->request->getPost('rmId', 'int');
        if ($rmId == null) {
            die('缺少参数');
        }
        $obj = XhtrackTch::findFirst($id);
        $image = $obj->toArray();
        if($fileType == 'fileDelete'){
            $images = explode(',', $image['sFiles']);
            $url = '';
            foreach ($images as $key => $value) {
                if ($key != $rmId && $value != '') {
                    $url = $url . $value . ',';
                }
            }
            $obj->sFiles = $url;
        }else{
            $images = explode(',', $image['sImages']);
            $url = '';
            foreach ($images as $key => $value) {
                if ($key != $rmId && $value != '') {
                    $url = $url . $value . ',';
                }
            }
            $obj->sImages = $url;
        }
        $result = $obj->save();
        if ($result) {
            return $this->sendSuccessResponse('成功');
        }
        return false;
    }

    public function ajaxDelete2Action($fileType=null)
    {
        $this->view->disable();
        $id = $this->request->getPost('id', 'string') or die('缺少参数id');
        $rmId = $this->request->getPost('rmId', 'int');
        if ($rmId == null) {
            die('缺少参数');
        }
        $obj = XhschoolPublicClass::findFirst($id);

        $image = $obj->toArray();
        if($fileType == 'fileDelete'){
            $images = explode(',', $image['sFiles']);
            $url = '';
            foreach ($images as $key => $value) {
                if ($key != $rmId && $value != '') {
                    $url = $url . $value . ',';
                }
            }
            $obj->sFiles = $url;
        }else {
            $images = explode(',', $image['sImages']);
            $url = '';
            foreach ($images as $key => $value) {
                if ($key != $rmId && $value != '') {
                    $url = $url . $value . ',';
                }
            }
            $obj->sImages = $url;
        }

        $result = $obj->save();
        if ($result) {
            return $this->sendSuccessResponse('成功');
        }
        return false;
    }






    /**
     * 公开课
     * created by dale 2017/11/3
     */
    public function publicClassAction(){
        Assets::viewer();
        Assets::datetimePicker();
        $this->di->get('assets')
            ->addCss('assets/fileinput/fileinput.css')
            ->addJs('../customer/js/fileinput.min.js')//修改过的
            ->addJs('../customer/js/zh.js');
        Assets::importJs('../customer/js/myMain.js');
        Assets::importJs('js/tch/publicClass.js');
        $this->view->pick('tch/tchTrack');
        $this->view->setVars([
            'addPower' => UserPower::checkUserPower('School_List_Tch_Add'),
        ]);
    }

    /**
     * 公开课表单
     * created by dale 2017113
     * modify by dale 20171211   --技术负责人默认 王伟松
     */
    public function pClassFormAction(){
        try {
            $iPCId = $this->request->getQuery('iPCId');
//            $tchId = $this->request->getQuery('iUserId', 'string');
            Assets::datetimePicker();
            Assets::easyUI();
            $this->di->get('assets')
                ->addCss('assets/fileinput/fileinput.css')
                ->addJs('../customer/js/fileinput.min.js')//修改过的
                ->addJs('../customer/js/zh.js');
            Assets::importJs('../customer/js/myMain.js');
            $this->view->pick('tch/pClassForm');
            Assets::importJs('js/tch/pClassForm.js');
            if($iPCId){
                $track = json_encode(XhschoolPublicClass::findFirst($iPCId)->toArray());
            }else{
                $tchStaff = XhhrmStaff::findFirst([
                    'conditions' => 'bDelete = 0 AND sStaffName = :sStaffName:',
                    'bind'       => ['sStaffName'=>'王伟松'],
                ]);
                if($tchStaff){
                    $arr['iTechChargeId'] =  $tchStaff->iUserId;
                    $track = json_encode($arr);
                }else {
                    $track = '1';
                }
            }
//            $apps  = App::getAppByUser($tchId, 4);
//            $apps  = Tool::getValue($apps, 'applications', []);
//            $newArr = [];
//            if ($apps) {
//                foreach ($apps as $app) {
//                    $newArr[] = [
//                        'id' => $app['packageName'],
//                        'text' => "{$app['appName']}({$app['versionName']})"
//                    ];
//                }
//            }
        $this->view->setVars([
            'trackInfo'=>$track,
            'iPCType' => XhsysEnum::getEnumByNodeName('公开课类别'),
//            'appArr'  => $newArr
        ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    public function getPublicClassAction(){
        $iUserId = $this->request->getPost('iUserId', 'int') or die('参数不足');
        $objs = XhschoolPublicClass::find([
            'conditions' => 'bDelete=0 AND iUserId = :iUserId:',
            'bind'       => ['iUserId'=>$iUserId],
            'order'      => 'tCreateDate desc'
        ]);
        return json_encode(array(
            'showDelete' => UserPower::checkUserPower('School_Teacher_PublicClass_Del'),
            'showEdit' => UserPower::checkUserPower('School_Teacher_PublicClass_Edit'),
            'data' => $this->pkTraceData($objs->toArray(),true),
        ));
    }

    /**
     * 保存公开课
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181129
     * modify by dale 20181129   添加应用  开始结束 时间
     */
    public function savePClassAction()
    {
        if(!User::isAdmin()&&
             !(UserPower::checkUserPower('School_Teacher_PublicClass_Add')
                || UserPower::checkUserPower('School_Teacher_PublicClass_Edit') )){
            return $this->sendErrorResponse(400,'缺少权限');
        }
        $iPCId   = $this->request->getPost('iPCId');
        $iUserId = $this->request->getPost('iUserId');
        if($iPCId){
            $obj = XhschoolPublicClass::findFirst($iPCId);
        }else{
            $obj = new XhschoolPublicClass();
        }
        $obj->assign($this->request->getPost());
        $obj->iAtClassChargeId = $this->request->getPost('iAtClassChargeId') =='' ? null:$this->request->getPost('iAtClassChargeId');
        $obj->iRunChargeId     = $this->request->getPost('iRunChargeId')     =='' ? null:$this->request->getPost('iRunChargeId');
        $obj->iWebChargeId     = $this->request->getPost('iWebChargeId')     =='' ? null:$this->request->getPost('iWebChargeId');
        $obj->iTechChargeId    = $this->request->getPost('iTechChargeId')    =='' ? null:$this->request->getPost('iTechChargeId');
        $obj->iMarkChargeId    = $this->request->getPost('iMarkChargeId')    =='' ? null:$this->request->getPost('iMarkChargeId');
        $obj->iPCType          = $this->request->getPost('iPCType')          =='' ? null:$this->request->getPost('iPCType');
        $obj->iStuNum          = $this->request->getPost('iStuNum')          =='' ? null:$this->request->getPost('iStuNum');
        $obj->iAttendNum       = $this->request->getPost('iAttendNum')       =='' ? null:$this->request->getPost('iAttendNum');
        if($obj->save()){
            $this->praseTchLog($iUserId,3);
            return $this->sendSuccessResponse('保存成功');
        }else{
            return $this->sendErrorResponse(500,'保存失败');
        }
    }

    public function pClassListAction(){
        $iUserId = $this->request->getQuery('iUserId');
        Assets::easyUI();
        Assets::viewer();
        Assets::importJs('js/tch/pClassList.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importMainJs('assets/easyui/datagrid-detailview.js');
        Assets::importJs('../customer/js/myMain.js');
        Assets::importJs('../ims/js/myTool.js');
        $this->view->pick('tch/pClassList');
        Template::exists('XHSchool_PublicClass', 'list') or die(Main::showMessageModal('XHSchool_PublicClass.xml 配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $listSearchArr = $listButtonArr2 = [];
        $classType = XhsysEnum::getEnumByNodeName('公开课类别');
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_classType',
            'data' =>  [0 => '类型'] + $classType, 'default' => '0','style' => 'width:60px;' );
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'list_depart', 'style' => 'width:120px;'];
        $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_StartTime', 'label' => ' 开始时间： ');
        $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_EndTime', 'label' => ' 结束时间： ');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');

        if(UserPower::checkUserPower('School_Teacher_PublicClass_Add')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '增加', 'icon' => 'fa-plus');
        }
        if(UserPower::checkUserPower('School_Teacher_PublicClass_Del')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        if(UserPower::checkUserPower('School_List_Tch_Feedback')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_feedback', 'text' => '添加反馈', 'icon' => 'fa-plus');
        }
        if(UserPower::checkUserPower('School_List_Tch_Feedback')){
            $listButtonArr2[] = array('plain' => 'true', 'id' => 'bt_list_feedback', 'text' => '添加反馈', 'icon' => 'fa-plus');
        }


        $configArr = [];
        if($iUserId){
//            $configArr['field']         = array('sUserName', 'tStartTime');
            $configArr['tableAttr']     = array('title'=>'');
            $configArr['buttonToolbar'] = Template::createButtonToolBar($listButtonArr);
        }else{
            $configArr['searchToolbar'] = Template::createSearchToolBar($listSearchArr,true);
            $configArr['buttonToolbar'] = Template::createButtonToolBar($listButtonArr2);
        }
        $this->view->setVars(array(
            'classList' => Template::createList('classList', 'XHSchool_PublicClass',$configArr),
        ));
    }

    public function getClassAction(){
        $startTime = $this->request->getPost('startTime');
        $endTime   = $this->request->getPost('endTime');
        $key       = $this->request->getPost('key');
        $iUserId   = $this->request->getPost('iUserId');
        $classType = $this->request->getPost('classType');
        $depart = $this->request->getPost('depart');

        try{
            $builder=$this->modelsManager->createBuilder()
                ->columns("p.iPCId,p.iUserId,p.tStartTime,p.iPCType,p.mContent,u.iSchoolId,s.sSchoolName,u.sUserName,p.sImages,p.sFiles,up.sSelfPhone,p.tEndTime,
                       p.sPlace,p.iStuNum,p.iAttendNum,p.sAttendClass,p.mAttendences,p.mDesc,p.iRunChargeId,p.iAtClassChargeId,p.mEvaluate,p.iEvalId,p.tEvalTime,
                       p.iWebChargeId,p.iTechChargeId,p.iMarkChargeId,p.tCreateDate,p.iCreateUserId,p.tLastModifyDate,p.iLastModifyUserId")
                ->from(['p'=>'Admin\Models\school\XhschoolPublicClass'])
                ->where('p.bDelete=0')->leftJoin('Admin\Models\user\XhsysUser','u.iUserId=p.iUserId','u')
                ->leftJoin('Admin\Models\user\XhsysUser','p.iEvalId=up.iUserId','up')
                ->leftJoin('Admin\Models\school\XhschoolInfo','s.iSchoolId=u.iSchoolId','s')->orderBy('p.tStartTime desc');
            if($startTime&&$endTime){
                $builder->andWhere('p.tStartTime>=:startTime: AND  p.tStartTime<=:endTime:',['startTime'=>$startTime,'endTime'=>$endTime]);
            }
            if($key){
                $builder->andWhere('u.sUserName like :key: or s.sSchoolName like :key:',['key'=>'%'.$key.'%']);
            }
            if($iUserId){
                $builder->andWhere('u.iUserId = :iUserId:',['iUserId'=>$iUserId]);
            }
            if ($classType) {
                $builder->andWhere('p.iPCType = :iPCType:', ['iPCType' => $classType]);
            }
            if ($depart) {
                $staff  = $this->db->fetchOne("select iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$depart},%'");
                $authId = $staff['iUserId'];
                if (!$authId) {
                    return $this->sendJsonResponse([]);
                }
                $schoolArr = User::getSchool(true, $authId, true);
                if (!empty($schoolArr)){
                    $schoolIds = implode(',', array_keys($schoolArr));
                    $schoolList = XhschoolInfo::find([
                        'conditions' => "bDelete = 0 AND (iStatus = 1 OR iStatus = 2) AND iSchoolId in ({$schoolIds})",
                        'columns'    => 'iSchoolId',
                    ])->toArray();
                    $schools = array_column($schoolList, 'iSchoolId');
                    $schools = '('.implode(',', $schools).')';
                    $builder->andWhere("s.iSchoolId in {$schools}");
                }
            }
            $data = Main::runBuilderPaginator($builder,true);
            Main::runUserNameById($data['rows'],['iCreateUserId'=>'iCreateUserId','iLastModifyUserId'=>'iLastModifyUserId','iEvalId'=>'iEvalId'],true);
        }catch (\Exception $e){
            die($e->getMessage());
        }
        $enums['iPCType'] = XhsysEnum::getEnumByNodeName('公开课类别');
        $downUrl = Main::getConfigByName('customer')['downUrl'];
        $this->runStaffNameById($data['rows'],['iAtClassChargeId'=>'iAtClassChargeId','iRunChargeId'=>'iRunChargeId','iWebChargeId'=>'iWebChargeId','iTechChargeId'=>'iTechChargeId','iMarkChargeId'=>'iMarkChargeId'],true);
        $showDel = UserPower::checkUserPower('School_List_Tch_Feedback');
        foreach ($data['rows'] as $index=>$row){
            $data['rows'][$index]['iPCType']     = $enums['iPCType'][$row['iPCType']];
            $data['rows'][$index]['tStartTime']  = date('Y-m-d H:i',strtotime($row['tStartTime']));
            $data['rows'][$index]['downUrl']     = $downUrl;
            $data['rows'][$index]['showDel']     = $showDel;

            if($row['sImages'] || $row['sFiles']){
                $data['rows'][$index]['fileInfo']    = '<i class="fa fa-file" aria-hidden="true" style="color:#2baab1;"></i>';
            }
            if ($row['mEvaluate'] != null) {
                $data['rows'][$index]['backInfo']    = '<i class="fa fa-comment" aria-hidden="true" style="color:#2baab1;"></i>';
            }

        }

        return $this->sendJsonResponse($data);
    }

    /**
     * 反馈
     * created by dale 2017/11/9
     */
    public function feedbackAction(){
        $iPCId = $this->request->getQuery('iPCId') or die('缺少参数');
        Assets::datetimePicker();
        Assets::easyUI();
        $this->di->get('assets')
            ->addCss('assets/fileinput/fileinput.css')
            ->addJs('../customer/js/fileinput.min.js')//修改过的
            ->addJs('../customer/js/zh.js');
        Assets::importJs('../customer/js/myMain.js');
        $this->view->pick('tch/feedback');
        Assets::importJs('js/tch/feedback.js');
        if($iPCId){
            $track = json_encode(XhschoolPublicClass::findFirst($iPCId)->toArray());
        }else{
            $track = '1';
        }
        $this->view->setVars([
            'trackInfo'=>$track,
        ]);
    }

    public function saveFeedbackAction(){
        try{
            $iPCId = $this->request->getPost('iPCId');
            $obj   = XhschoolPublicClass::findFirst($iPCId);
            $iUserId =$obj->iUserId;
            $obj ->assign($this->request->getPost());
            $obj->iEvalId = Main::getLoginUserInfo('userId');
            $obj->tEvalTime = date('Y-m-d H:i:s',time());
            if($obj->save()){
                $this->praseTchLog($iUserId,4);
                return $this->sendSuccessResponse('反馈成功');
            }else{
                return $this->sendErrorResponse(500,'反馈失败');
            }
        }catch (\Exception $e){
            die($e->getMessage());
        }
    }


    public function templateAction(){
        $this->view->pick('tch/template');
        Assets::importJs('js/tch/template.js');
        $infos = XhsysTemplate::find([
            'conditions' => 'iTPType = :iTPType: AND bDelete=0',
            'bind'       => ['iTPType'=>1]
        ]);
        if($infos->toArray()==[]){
            $flag=false;
        }else{
            $flag=true;
        }
        $this->view->setVars([
            'infos'    => $infos->toArray(),
            'flag'     =>  $flag,
        ]);
    }

    public function saveTemplateAction(){
        $iTPId = $this->request->getPost('iTPId');
        if($iTPId){
            $obj = XhsysTemplate::findFirst($iTPId);
        }else{
            $obj = new XhsysTemplate();
        }
        $obj->assign($this->request->getPost());

        if($obj->save()){
            return $this->sendSuccessResponse('添加成功');
        }else{
            return $this->sendErrorResponse(500,'添加失败');
        }
    }

    public function delTpAction($iTPId){
        if(!$iTPId){
            return $this->sendErrorResponse(500,'缺少参数iTPId');
        }
        $obj = XhsysTemplate::findFirst($iTPId);
        $obj->bDelete = 1;
        $res = $obj->save();
        if($res){
            return $this->sendSuccessResponse('删除成功');
        }else{
            return $this->sendErrorResponse(500,'删除失败');
        }
    }

    public function getTpAction($iTPId){
        $info = XhsysTemplate::findFirst($iTPId);
        if(!$info){
            return $this->sendErrorResponse(500,'模板不存在');
        }else{
           return $this->sendJsonResponse($info->toArray());
        }
    }

    /**
     * 获取部门
     * @param $tag 部门标签
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/11/8
     */
    public function getStaffAction($tag){
        $data = XhhrmStaff::getDepStaffByTag($tag,true);
        return $this->sendJsonResponse($data);
    }

    public static function runPhoneById(&$obj, $fields, $isArray)
    {
        $userIdArr = [];
        is_string($fields) and $fields = [$fields => $fields];
        if($isArray){
            foreach($fields as $idField => $nameField){
                $userIdArr = array_merge($userIdArr, array_column($obj, $idField));
            }
            $userNameArr = XhhrmStaff::getPhoneById($userIdArr);
            foreach($obj as $index => $objOne){
                foreach($fields as $idField => $nameField){
                    if(!isset($userNameArr[$objOne[$idField]])) continue;
                    $obj[$index][$nameField] =  $userNameArr[$objOne[$idField]];
                }
            }
        }
        else{
            foreach($fields as $idField => $nameField){
                $userIdArr = array_merge($userIdArr, $obj[$idField]);
            }
            $userNameArr = XhhrmStaff::getPhoneById($userIdArr);
            foreach($fields as $idField => $nameField){
                if(!isset($userNameArr[$obj[$idField]])) continue;
                $obj[$nameField] =  $userNameArr[$obj[$idField]];
            }
        }
    }


    public static function runStaffNameById(&$obj, $fields, $isArray)
    {
        $userIdArr = [];
        is_string($fields) and $fields = [$fields => $fields];
        if($isArray){
            foreach($fields as $idField => $nameField){
                $userIdArr = array_merge($userIdArr, array_column($obj, $idField));
            }
            $userNameArr = XhhrmStaff::getStaffNameById($userIdArr);
            foreach($obj as $index => $objOne){
                foreach($fields as $idField => $nameField){
                    if(!isset($userNameArr[$objOne[$idField]])) continue;
                    $obj[$index][$nameField] =  $userNameArr[$objOne[$idField]];
                }
            }
        }
        else{
            foreach($fields as $idField => $nameField){
                $userIdArr = array_merge($userIdArr, $obj[$idField]);
            }
            $userNameArr = XhhrmStaff::getStaffNameById($userIdArr);
            foreach($fields as $idField => $nameField){
                if(!isset($userNameArr[$obj[$idField]])) continue;
                $obj[$nameField] =  $userNameArr[$obj[$idField]];
            }
        }
    }

    public function timeAction(){
//        $state = [0 => '未上线', 1 => '上线', 2 => '运营', 3 => '停运', 4 => '测试'];
        $iStatus = [
            1   => '上线',
            2   => '运营',
        ];
        $this->view->pick('tch/time');
        Assets::datetimePicker();
        Assets::importJs('../ims/js/myTool.js');
        Assets::importJs('js/tch/time.js');
        $dep = XhhrmDepart::findFirst([
            'columns'    => 'iDepId,sDepName',
            'conditions' => 'bDelete = 0 AND sTag = :sTag:',
            'bind'       => ['sTag'=>'XHYYB']
        ]);
        $area = XhhrmDepart::find([
            'columns'    => 'iDepId,sDepName,iParentId',
            'conditions' => 'bDelete = 0 AND iParentId = :iParentId:',
            'bind'       => ['iParentId'=>$dep->iDepId],
        ]);
        $area = array_column($area->toArray(),'sDepName','iDepId');
        $this->view->setVars([
            'area' => $area ,
            'status' =>$iStatus,
        ]);
    }

    public function getDepsAction($pId){
        $data = XhhrmDepart::getDeps($pId);
        return $this->sendJsonResponse($data);
    }

    /**
     * 刷题王做题统计
     *
     *
     * created by dale 20171124
     * modified by dale 2017127
     */
    public function countExerciseAction(){
        $type = $this->request->getQuery('type');
        if(!$type){ //没有type,做题统计
            $this->view->pick('tch/countExercise');
        }else{ //有type,点题统计
            $this->view->pick('tch/countTopic');
        }
        Assets::datetimePicker();
        Assets::easyUI('js/tch/countExercise.js');
        Template::exists('XHSchool_Info', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106010));
        $schSearchArr = [];
        $schSearchArr[] = ['type'=>'text', 'id'=>'SchoolList_Search','style'=>'width:100px;','label'=>'搜索：'];
        $schSearchArr[] = ['type'=>'button', 'id'=>'bt_SchoolList_Search', 'text'=>'确定', 'icon'=>'fa-search', 'style'=>'margin-left:5px'];
        $schSearchArr[] = ['type'=>'button', 'id'=>'bt_SchoolList_Time','icon'=>'fa-binoculars', 'text'=>'更多查询', 'style'=>'margin-left:5px'];

        $this->view->setVars([
            'SchoolList'    => Template::createList('SchoolList', 'XHSchool_Info', [
                'searchToolbar' => Template::createSearchToolBar($schSearchArr),
                'checkbox'      => true,
                'field'         => ['sSchoolName'],
                'tableAttr'     => ['singleSelect' => 'true']
            ]),
        ]);
    }

    /**
     * 获取学校数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 20171124
     */
    public function getSchAction(){
        $key     = $this->request->getPost('key');
        $schCity   = $this->request->getPost('schCity');
        $schArea   = $this->request->getPost('schArea');
        $sql = 'select iSchoolId,sSchoolName from XHSchool_Info where bDelete = 0 AND iStatus in (1,2)';
        if($schArea&&$schCity){

            $staffSql = "select  iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$schCity},%'"; //取第一个
            $staffs = $this->db->query($staffSql)->fetchAll(\PDO::FETCH_ASSOC);
            $authId = !isset($staffs[0]['iUserId']) ?  null : $staffs[0]['iUserId'];
            $schoolIds = UserPower::getAuthorizationSchool(false,$authId);
        }else if($schArea){
            $staffSql = "select  iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$schArea},%'"; //取第一个
            $staffs = $this->db->query($staffSql)->fetchAll(\PDO::FETCH_ASSOC);
            $authId = !isset($staffs[0]['iUserId']) ?  null : $staffs[0]['iUserId'];
            $schoolIds = UserPower::getAuthorizationSchool(false,$authId);

        }else{
            $schoolIds = UserPower::getAuthorizationSchool(false);
        }
        if ($schoolIds === false) {

        } else if ($schoolIds !== true) {
            $sql .= ' AND iSchoolId IN (' . implode(',', $schoolIds) . ') ';

        }
        if($key){
            $sql .=" AND sSchoolName like '%{$key}%' ";
        }

        $data  = Main::runSqlPage(['query'=>"select :columns: from ({$sql}) as td",'columns'=>'td.*']);

        return $this->sendJsonResponse($data);
    }

    /**
     * 更多搜索
     *
     * created by dale 20171124
     */
    public function moreSearchAction(){
        $this->view->pick('tch/time');
        Assets::datetimePicker();
        Assets::importJs('../ims/js/myTool.js');
        Assets::importJs('js/tch/moreSearch.js');
        $dep = XhhrmDepart::findFirst([
            'columns'    => 'iDepId,sDepName',
            'conditions' => 'bDelete = 0 AND sTag = :sTag:',
            'bind'       => ['sTag'=>'XHYYB']
        ]);
        $area = XhhrmDepart::find([
            'columns'    => 'iDepId,sDepName,iParentId',
            'conditions' => 'bDelete = 0 AND iParentId = :iParentId:',
            'bind'       => ['iParentId'=>$dep->iDepId],
        ]);
        $area = array_column($area->toArray(),'sDepName','iDepId');
        $this->view->setVars([
            'area' => $area ,
        ]);
    }

    /**
     * 审核界面
     *
     * create by dale 2017125
     */
    public function checkAction(){
        $iTTchId = $this->request->getQuery('iTTchId');
        $this->view->pick('tch/check');
        Assets::importJs('js/tch/check.js');
        $track = XhtrackTch::findFirst($iTTchId);
        $check = '';
        if ($track){
//            if ($track->iState == 2 && Main::getLoginUserInfo('logonName') != 'admin'){
//                $check = "parent.$('#bt_modal_confirm').hide();parent.$('#bt_modal_close').hide();";
//            }
            $track = json_encode($track->toArray());
        }else{
            $track = '1';
        }
        $this->view->setVars([
            'trackInfo' => $track,
            'check'     => $check,
        ]);
    }

    /**
     * 保存审核踪迹
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 2017125
     */
    public function saveTrackCheckAction()
    {
        try {
            $iTTchId = $this->request->getPost('iTTchId','int');
            $msgId = $this->request->getPost('msgId','int');
            if (!$iTTchId){
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XhtrackTch::findFirst($iTTchId);
            $obj->assign($this->request->getPost());
            if($obj->save()){
//                if ($msgId) {
//                    Msg::setReadMsg([$msgId]);
//                }
//                Msg::setMsg('tch_log', [$obj->iTTchId]);
                return $this->sendSuccessResponse('操作成功');
            }else{
                return $this->sendSuccessResponse('审核失败');
            }
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }


    /**
     * 获取本月每个学校的公开课次数
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string  {"149":"2","900090009":"1"}
     *
     * create by dale 20171219
     */
    public function getMonthClassAction(){
        try{
            $startMonth = date('Y').'-'.date('m').'-01';
            $endMonth   = date('Y-m-d',mktime(0,0,0,date('m')+1,1,date('Y'))-24*3600);
            $sql = "select count(p.iPCId) as num,u.iSchoolId from XHSchool_PublicClass as p 
                LEFT  JOIN XHSys_User as u ON u.iUserId = p.iUserId
                WHERE p.bDelete = 0 AND DATE_FORMAT(p.tStartTime,'%Y-%m-%d') >= '{$startMonth}' AND  DATE_FORMAT(p.tStartTime,'%Y-%m-%d') <= '{$endMonth}' GROUP BY u.iSchoolId";
            $data = $this->db->fetchAll($sql);
            $data = array_column($data,'num','iSchoolId');
            return json_encode($data);
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 使用应用
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale 20180257
     */
    public function tchAppAction()
    {
        $this->view->pick('tch/tchApp');
        Assets::select2('js/tch/tchApp.js');
        return $this->view->setVars([
            'schoolArr' => User::getSchool(true),
            'start'     => date('Y-m-d',strtotime('-7day')),
            'end'       => date('Y-m-d',strtotime('today'))
        ]);
    }

    public function tchAppFixAction()
    {
        $this->view->pick('tch/tchAppFix');
        $schoolId       = $this->request->getQuery('schoolId', 'int');
        $startTime      = $this->request->getQuery('startTime', 'string');
        $endTime        = $this->request->getQuery('endTime', 'string');
        $userId         = $this->request->getQuery('userId', 'int');

        if (!$schoolId || !$startTime || !$endTime) {
            return $this->sendViewError('缺少必要参数');
        }
        if ($startTime > time()) {
            return $this->sendViewError('日期超出限制，不可查询');
        }
        try {
            $statsSchool = new StatsschoolController();
            $appUsage = $statsSchool->getTchAppUsage($schoolId, $startTime, $endTime, ['userId'=>$userId]);
            return $this->view->setVars([
                'appUsage'      => $appUsage,
            ]);
        }
        catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    public function tchTrackHomeAction($schoolId){
        $this->view->pick('tch/tchTrackHome');
        $builder = $this->modelsManager->createBuilder()
                    ->columns('t.iTrackType,t.iTTchId,t.tTrackTime,u.iSchoolId,t.iState')
                    ->from(['t'=>'Admin\\Models\\track\\XhtrackTch'])
                    ->leftJoin('Admin\\Models\\user\\XhsysUser','t.iUserId = u.iUserId','u')
                    ->where('t.bDelete = 0 and u.iSchoolId = :schoolId: AND t.iState = 2 ', [ 'schoolId' => $schoolId ])
                    ->orderBy('t.tTrackTime desc')->limit(6);

        $tracks = $builder->getQuery()->execute()->toArray();
        $iTrackType = XhsysEnum::getEnumByNodeName('教师跟踪类型');
        foreach ($tracks as $index => $rows){
            $tracks[$index]['iTrackType'] = isset($rows['iTrackType']) ?  $iTrackType[$rows['iTrackType']] : '未知';
            $tracks[$index]['tTrackTime'] = date('Y-m-d',strtotime($rows['tTrackTime']));
        }
        $this->view->setVars([
            'tracks' => $tracks,
            'schoolName' => XhschoolInfo::getSchoolArray()[$schoolId],
        ]);
    }

//    public function testAction()
//    {
//        $arr = [ '', 1, 2];
//        var_dump(array_unique($arr));die;
//    }


}
